/**   
 * @Title: LoginActivity.java 
 * @Package com.fone.player.activity.personal
 * Copyright: Copyright (c) 2014
 * Company: 100TV
 * @Description: 登录模块 包括第三方登录) 
 * @author JasonZue  jczhe@100tv.com   
 * @date 2014-4-25 下午5:02:09 
 * @version V1.0   
 */

package com.fone.player.activity.personal;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.activity.pay.FoneThirdPayActivity;
import com.fone.player.bean.LoginData;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.LoginspaceRst;
import com.fone.player.client.Reporter;
import com.fone.player.client.Request;
import com.fone.player.constant.FoneConstant;
import com.fone.player.sns.ISNSLoginManager;
import com.fone.player.sns.ISNSLoginManager.AuthorizingStateListener;
import com.fone.player.sns.UserInfoManager;
import com.fone.player.sns.bean.SNSUserInfo;
import com.fone.player.sns.impl.SNSLoginManager;
import com.fone.player.sns.util.SNSUtil;
import com.fone.player.util.ActivityQueue;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.LoginUtil;
import com.fone.player.util.SerializationUtil;
import com.fone.player.view.UserListPopwindow;

/**
 * 登录模块
 * 
 * @author JasonZue
 * @since 2014-4-25
 */

public class LoginActivity extends BaseActivity implements OnClickListener {

	private static final String TAG = "LoginActivity";

	private TextView mTitleTv;
	private Button mLeftBt, mRightBt, mLoginBt;
	private RelativeLayout mLoginTencentqq;
	private RelativeLayout mLoginSinaweibo;
	private RelativeLayout mLoginTencentweibo;
	private RelativeLayout mLoginTencentweixin;
	private RelativeLayout userNameRl;
	private LinearLayout mWaitting;
	private SNSLoginManager mSNSLoginManager;
	public CheckBox loginUserlistCb;

	public EditText usernameEt, pswEt;
	private UserListPopwindow mUserListPopwindow;
	private int offsetX = 0;
	private int usernamePopWidth = 0;
	private ArrayList<String> userList;

	private LoginCallBack mLoginCallBack;

	private IntentFilter intentFilter;
	private BroadcastReceiver loginSuccessBr;

	private Handler mHandler;
	private static final int LOGIN_SUCCESS = 1;
	private String mFromPage ;//标记从计费页面跳转到登录界面 点击返回时取消计费
	private String mPayFrom ,mclid;//标记从计费页面跳转到登录界面 登录成功后回到计费页面 的计费来源
	private int mFeeType = -1;//标记从计费类型 

	private String tempName = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personal_login_view);
		initView();
		iniData();
		iniHandler();
		iniLoginSuccessReceiver();
	}

	/**
	 * 初始化视图
	 * 
	 * @return void
	 * @throws
	 */
	private void initView() {
		mLeftBt = (Button) findViewById(R.id.common_title_left_bt);
		mRightBt = (Button) findViewById(R.id.common_title_right_bt);
		mLoginBt = (Button) findViewById(R.id.login_logining_bt);
		mTitleTv = (TextView) findViewById(R.id.common_title_text_tv);

		mLeftBt.setText("登录");
		mRightBt.setText("注册帐号");
		mTitleTv.setVisibility(View.GONE);

		mLoginTencentqq = (RelativeLayout) findViewById(R.id.login_tencent_qq_rl);
		mLoginSinaweibo = (RelativeLayout) findViewById(R.id.login_sina_weibo_rl);
		mLoginTencentweibo = (RelativeLayout) findViewById(R.id.login_tencent_weibo_rl);
		mLoginTencentweixin = (RelativeLayout) findViewById(R.id.login_tencent_weixin_rl);
		mWaitting = (LinearLayout) findViewById(R.id.login_waitting_ll);

		loginUserlistCb = (CheckBox) findViewById(R.id.login_userlist_cb);
		userNameRl = (RelativeLayout) findViewById(R.id.login_user_name_rl);
		usernameEt = (EditText) findViewById(R.id.login_user_name_et);
		pswEt = (EditText) findViewById(R.id.login_user_pwd_et);

		mLoginTencentqq.setOnClickListener(this);
		mLoginSinaweibo.setOnClickListener(this);
		mLoginTencentweibo.setOnClickListener(this);
		mLoginTencentweixin.setOnClickListener(this);
		mLoginBt.setOnClickListener(this);
		mRightBt.setOnClickListener(this);
		mLeftBt.setOnClickListener(this);
		mWaitting.setOnClickListener(this);

		usernameEt.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					userNameRl.setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.com_import_click));
				} else {
					userNameRl.setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.com_import));
				}
			}
		});
	}
	/**
	 * 注册登录成功广播接收
	 */
	private void iniLoginSuccessReceiver(){
		if(intentFilter==null){
			intentFilter = new IntentFilter();
			intentFilter.setPriority(200);
			intentFilter.addAction(FoneConstant.BROADCAST_LOGIN_SUCCESS);
		}
		if(loginSuccessBr==null){
			loginSuccessBr = new BroadcastReceiver(){

				@Override
				public void onReceive(Context context, Intent intent) {
					L.v(TAG, "iniLoginSuccessReceiver", "onReceive  loginsuccess ");
					finish();
				}
			};
			L.v(TAG, "iniLoginSuccessReceiver", "loginSuccessBr  register ");
			this.registerReceiver(loginSuccessBr, intentFilter);
		}
	}
	
	/**
	 * 初始化数据
	 */
	private void iniData() {
		// 获取用户名图片的宽度
		iniManager();
		mLoginCallBack = new LoginCallBack();
		Intent intent = getIntent();
		mFromPage = intent.getStringExtra("loginfrom");
		mPayFrom = intent.getStringExtra("payfrom");
		mclid = intent.getStringExtra("clid");
		mFeeType = intent.getIntExtra("type", -1);
//		userList = intent.getStringArrayListExtra("userlist");
		userList = SerializationUtil.readUserListSerialization(mContext, UserInfoManager.HISTORICALUSERLIST);
		
		if (userList != null && userList.size() > 0) {
			iniUsernamePop();
		}
	}

	private void iniUsernamePop() {

		loginUserlistCb.setVisibility(View.VISIBLE);
		ViewTreeObserver viewTreeObserver = this.getWindow().getDecorView()
				.getViewTreeObserver();
		viewTreeObserver
				.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

					@Override
					public void onGlobalLayout() {
						LoginActivity.this.getWindow().getDecorView()
								.getViewTreeObserver()
								.removeGlobalOnLayoutListener(this);

						offsetX = getResources().getDrawable(
								R.drawable.loading_user).getMinimumWidth() * 7 / 8;
						usernamePopWidth = userNameRl.getWidth() - offsetX;

						mUserListPopwindow = new UserListPopwindow(
								LoginActivity.this,usernamePopWidth, userList);
						loginUserlistCb
								.setOnCheckedChangeListener(new OnCheckedChangeListener() {

									@Override
									public void onCheckedChanged(
											CompoundButton buttonView,
											boolean isChecked) {
										if (isChecked
												&& !mUserListPopwindow
														.isShowing()) {
											mUserListPopwindow.show(userNameRl,
													offsetX);
										} else if (!isChecked
												&& mUserListPopwindow
														.isShowing()) {
											mUserListPopwindow.dismiss();
										}
									}
								});
						loginUserlistCb.setChecked(true);
					}
				});
		}

	@SuppressLint("HandlerLeak")
	private void iniHandler() {
		mHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case LOGIN_SUCCESS:
					FoneUtil.sendLoginSuccess(mContext, mPayFrom, mFeeType,
							false,mclid);
					mWaitting.setVisibility(View.GONE);
					FoneUtil.showToast(mContext, "登录成功");
					break;
				default:
					break;
				}
			}
		};
	}

	/**
	 * 初始化SNSManager
	 */
	private void iniManager() {
		mSNSLoginManager = SNSLoginManager.getInstance();
		mSNSLoginManager
				.setAuthiringStateListener(new MyAuthorizingStateListener());
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_tencent_qq_rl:// QQ
			if (FoneUtil.isNetOkWithToast(mContext)) {
				mSNSLoginManager
						.authorizeByType(ISNSLoginManager.TENCENT_QQ_TYPE);
			}
			break;
		case R.id.login_sina_weibo_rl:// sina
			if (FoneUtil.isNetOkWithToast(mContext)) {
				mSNSLoginManager
						.authorizeByType(ISNSLoginManager.SINA_WEIBO_TYPE);
			}
			break;
		case R.id.login_tencent_weibo_rl:// Tencent_weibo
			if (FoneUtil.isNetOkWithToast(mContext)) {
				mSNSLoginManager
						.authorizeByType(ISNSLoginManager.TENCENT_WEIBO_TYPE);
			}
			break;
		case R.id.login_tencent_weixin_rl:// Tencent_weixin
			if (FoneUtil.isNetOkWithToast(mContext)) {
				mSNSLoginManager
				.authorizeByType(ISNSLoginManager.TENCENT_WEIXIN_TYPE);
			}
			break;
		case R.id.login_logining_bt:// 100tv
			// 隐藏输入法
			InputMethodManager imm = (InputMethodManager) mContext
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			if (imm != null) {
				imm.hideSoftInputFromWindow(mLoginBt.getWindowToken(), 0);
			}

			String userName = usernameEt.getText().toString();
			String psw = pswEt.getText().toString();

			if (FoneUtil.isNetOkWithToast(mContext)) {
				if (verifyRegister(userName, psw)) {
					// 请求网络
					tempName = userName;
					mWaitting.setVisibility(View.VISIBLE);
					LoginData data = LoginUtil.getLoginData(userName, psw);
					login(data,1);
				}
			}
			break;
		case R.id.common_title_right_bt:
			// 注册
			Intent intent = new Intent(this, RegistActivity.class);
			intent.putExtra("type", mFeeType);
			intent.putExtra("payfrom", mPayFrom);
			intent.putExtra("clid", mclid);
			intent.putExtra("loginfrom", getIntent().getStringExtra("loginfrom"));
			startActivity(intent);
			break;
		case R.id.common_title_left_bt:
			// 返回
			backFromLogin();
			break;
		default:
			break;
		}
	}

	private void backFromLogin() {
		Activity currentActivity, lastActivity;
//		if (FoneConstants.FROM_BE_VIP.equals(mFromPage)
//				|| FoneConstants.FROM_VIP_FILM.equals(mFromPage)
//				|| FoneConstants.FROM_CHARGE_VB.equals(mFromPage)) {
//			lastActivity = ActivityQueue.popIndex(1);
//			lastActivity.finish();
//		}
		L.i(TAG, "计费来源"+mPayFrom+"计费类型"+mFeeType+"栏目ID"+mclid);
		if ((null != mPayFrom && !("".equals(mPayFrom)))|| mFeeType == 2) {
			L.i(TAG, "计费来源"+mPayFrom+"计费类型"+mFeeType+"栏目ID"+mclid+"未登录返回入口处");
			lastActivity = ActivityQueue.popIndex(1);
			if(null != lastActivity && lastActivity instanceof FoneThirdPayActivity){
				lastActivity.finish();
			}
		}
		currentActivity = ActivityQueue.popIndex(0);
		currentActivity.finish();
	}

	public boolean verifyRegister(String userName, String password) {
		L.v(TAG, "verifyRegister", "userName : " + userName + " password : "
				+ password);
		boolean verifyRes = true;
		if (userName == null || userName.trim().equals("")) {
			Toast.makeText(mContext, "请输入用户名", Toast.LENGTH_SHORT).show();
			verifyRes = false;
		} else if (password == null || password.equals("")) {
			Toast.makeText(mContext, "请输入密码", Toast.LENGTH_SHORT).show();
			verifyRes = false;
		}
		if (verifyRes) {
			if (!LoginUtil.checkEmailAndMobile(userName)) {
				Toast.makeText(mContext, "请输入正确邮箱或手机号", Toast.LENGTH_SHORT)
						.show();
				verifyRes = false;
			} else if (!LoginUtil.checkPassword(password)) {
				Toast.makeText(mContext, "密码由6-24位英文数字组成", Toast.LENGTH_SHORT)
						.show();
				verifyRes = false;
			}
		}
		return verifyRes;
	}

	/**
	 * SNS授权监听类
	 * 
	 * @author user 用户信息
	 * 
	 */
	private class MyAuthorizingStateListener implements
			AuthorizingStateListener {

		@Override
		public void authrizeAction(int action, String info) {

			switch (action) {
			case AuthorizingStateListener.AUTHORIZING:
				L.v(TAG, "authrizeAction", "AUTHORIZING");
				mWaitting.setVisibility(View.VISIBLE);
				break;
			case AuthorizingStateListener.AUTHORIZE_SUCCESS:
				L.v(TAG, "authrizeAction", "AUTHORIZE_SUCCESS");
				// Toast.makeText(LoginActivity.this, "授权成功",
				// Toast.LENGTH_SHORT).show();
				break;
			case AuthorizingStateListener.AUTHORIZE_CANCEL:
				L.v(TAG, "authrizeAction", "AUTHORIZE_CANCEL");
				mWaitting.setVisibility(View.GONE);
				break;
			case AuthorizingStateListener.AUTHORIZE_ERROR:
				L.v(TAG, "authrizeAction", "AUTHORIZE_ERROR");
				mWaitting.setVisibility(View.GONE);
				Toast.makeText(LoginActivity.this, info, Toast.LENGTH_SHORT)
						.show();
				break;
			default:
				break;
			}
		}

		@Override
		public void onUserInfoComplete(SNSUserInfo user) {
			// Toast.makeText(LoginActivity.this, "获取了userInfo...",
			// Toast.LENGTH_SHORT).show();
			L.v(TAG, "onUserInfoComplete", "userInfo : " + user);
			mWaitting.setVisibility(View.VISIBLE);
			LoginData data = LoginUtil.getLoginData(user);
			login(data,0);
		}
	}

	private class LoginCallBack implements Callback<LoginspaceRst> {

		@Override
		public void onSuccess(final LoginspaceRst t) {
			L.v(TAG, "LoginCallBack onSuccess", t.toString());
			if (t.result != 0) {
				tempName = null;
				if (t.error != null) {
					try {
						switch (Integer.valueOf(t.error.errorcode)) {
						case 110:// 用户名不存在
						case 111:// 用户名或密码错误
						case 117:// 请检查用户名
							FoneUtil.showToast(mContext, "帐号密码不匹配");
							break;
						default:
							FoneUtil.showToast(mContext, "登录失败");
							break;
						}
					} catch (Exception e) {
						FoneUtil.showToast(mContext, "登录失败");
					}
					Reporter.logError("", 5);//登陆失败上报
					// 清除所有授权
					SNSLoginManager.getInstance().CancelAllAuthSNS();
					mWaitting.setVisibility(View.GONE);
					return;
				}
			}
			// 本地化用户信息
			new Thread() {
				@Override
				public void run() {
					UserInfoManager.saveLoginUserInfo(t,
							UserInfoManager.NEW_USER);
					UserInfoManager.saveHistoricalUserList(tempName);
					tempName = null;
					mHandler.sendEmptyMessage(LOGIN_SUCCESS);
				};
			}.start();

		}

		@Override
		public void onFailure(Error error) {
			mWaitting.setVisibility(View.GONE);
			tempName = null;
			L.v(TAG,
					"LoginCallBack onFailure",
					"isNetworkError : " + error.isNetworkError() + " status : "
							+ error.getStatus() + " reason : "
							+ error.getReason());

			Reporter.logError("", 5);//登陆失败上报
			SNSLoginManager.getInstance().CancelAllAuthSNS();
			if (error.isNetworkError()) {
				FoneUtil.showToast(mContext, "网络超时,请稍后重试");
				return;
			}
			FoneUtil.showToast(mContext, "登录失败");
		}

	}

	/**
	 * @param data
	 * @param type 主账户1  第三方0
	 */
	private void login(LoginData data,int type){
		
		// 点击权利页按钮跳转到登陆   入口是否只有  付费影片计费
		//mFromPage	1 点击头像注册 2 点击立即充值 3 点击成为VIP 4 付费影片计费注册  5点击vip频道 加入vip按钮 6 点击权利页按钮跳转到登陆 7 其他
		
		int loginFrom = 0;
		switch (FoneUtil.String2Integer(mFromPage)) {
		case 1: // 点击头像
			loginFrom = 60;
			break;
		case 2: // 点击我的视频中“马上充值”按钮
			loginFrom = 65;
			break;
		case 3: // 点击我的视频中“加入VIP”按钮
			loginFrom = 61;
			break;
		case 4: // 来自付费影片计费
			loginFrom = 63; //付费影片->vip权利页->点击按钮->到登陆页
			break;
		case 5: // vip频道中点击加入vip
			loginFrom = 62;
			break;
		case 6: // 点击权利页按钮跳转到登陆
			loginFrom = 63;
			break;
		default:
			loginFrom = 0;
			break;
		}
		
		int loadway = 0;
		if(type == 1||TextUtils.isEmpty(data.fp)){//主账户
			loadway=1;
		}else if("qq".equals(data.fp)){//QQ
			loadway = 2;
		}else if("sina".equals(data.fp)){//腾讯微博
			loadway = 3;
		}else if("tencent".equals(data.fp)){//sina
			loadway = 4;
		}else if("wechat".equals(data.fp)){//wechat
			loadway = 5;
		}
		
		L.v(TAG, "login"," loadway : " + loadway + " loginFrom : " + loginFrom);
		
		Request.getInstance().loginspace(type,loadway,loginFrom,data, mLoginCallBack);
	}

	@Override
	public void onBackPressed() {
		// super.onBackPressed();
		backFromLogin();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mWaitting.getVisibility() == View.VISIBLE) {
			mWaitting.setVisibility(View.VISIBLE);
			SNSUtil.stopSNS();
		}
		if(loginSuccessBr!=null){
			this.unregisterReceiver(loginSuccessBr);
			loginSuccessBr = null;
		}
	}
}
